package com.gexiaobao.pigeon.ui.activity

import android.app.Application
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.OnBackPressedCallback
import androidx.navigation.Navigation
import com.alibaba.ha.adapter.AliHaAdapter
import com.alibaba.ha.adapter.AliHaConfig
import com.alibaba.ha.adapter.Plugin
import com.alibaba.sdk.android.push.notification.AdvancedCustomPushNotification
import com.alibaba.sdk.android.push.notification.CustomNotificationBuilder
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.appViewModel
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.model.param.OutChatParam
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.DeviceUtil
import com.gexiaobao.pigeon.app.util.MarketUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityMainBinding
import com.gexiaobao.pigeon.ui.dialog.RxDialogUpdateApp
import com.gexiaobao.pigeon.viewmodel.MainViewModel
import com.taobao.sophix.SophixManager
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.util.LogUtils

class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {

    var exitTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel.upDateVersion()
        /** 初始化阿里云崩溃分析 */
        initHa()
        /** 设置自定义推送消息布局 */
        setBasicCusNotification()
        /** 拉取最新补丁包 */
        SophixManager.getInstance().queryAndLoadNewPatch()
        if (CacheUtil.isFirstAddress()) {
            mViewModel.getAddressList()
        }

        eventViewModel.toRefreshData.observeInActivity(this) {
            mViewModel.getAddressList()
        }

        eventViewModel.toNotifyOutChat.observeInActivity(this) {
            val body = OutChatParam(talkUserId = it)
            mViewModel.outChat(body)
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val nav = Navigation.findNavController(this@MainActivity, R.id.host_fragment)
                if (nav.currentDestination != null && nav.currentDestination!!.id != R.id.mainfragment) {
                    //如果当前界面不是主页，那么直接调用返回即可
                    nav.navigateUp()
                } else {
                    //是主页
                    if (System.currentTimeMillis() - exitTime > 2000) {
                        RxToast.showToast(getString(R.string.exit_program))
                        exitTime = System.currentTimeMillis()
                    } else {
                        finish()
                    }
                }
            }
        })
        appViewModel.appColor.value?.let {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            supportActionBar?.setBackgroundDrawable(ColorDrawable(it))
            StatusBarUtil.setColor(this, it, 0)
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取版本信息 */
        mViewModel.versionResult.observe(this) { resultState ->
            parseState(resultState, {
                val currentVersionCode = DeviceUtil.getVersionCode(this)
                val code = it.code
                if (it.url.isNotEmpty()) {
                    if (currentVersionCode < code) {//1-强更 2-不强更
                        showGoMarketUpdate(it.version)
                    }
                }
            }, {
                LogUtils.warnInfo(it.msg)
            })
        }
        /** 请求收货地址信息 */
        mViewModel.addressResult.observe(this) {
            CacheUtil.setFirstAddress(false)
            if (!it.isEmpty && it.listData != null) {
                it.listData.forEachIndexed { _, listBean ->
                    if (listBean.addressType == 1) {//1默认2不默认
                        CacheUtil.setAddressInfo(listBean)
                        return@observe
                    }
                    CacheUtil.setAddressInfo(it.listData[0])
                }
            }
        }

        appViewModel.appColor.observeInActivity(this) {
            supportActionBar?.setBackgroundDrawable(ColorDrawable(it))
            StatusBarUtil.setColor(this, it, 0)
        }
    }

    /** 去应用商店更新app */
    private fun showGoMarketUpdate(version: String) {
        val dialog = RxDialogUpdateApp(this)
        dialog.setTitle(getString(R.string.New_version_detected) + version + "\n" + getString(R.string.update_is_ready_to_install))
        dialog.setSureListener {
            MarketUtils.getTools().startMarket(this, this.packageName)
        }
        dialog.setCanceledOnTouchOutside(false)
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun initHa() {
        val config = AliHaConfig()
        config.appKey = "333827899"
        config.appVersion = DeviceUtil.getVerName(this)
        config.appSecret = "72c1e171648b45de87e0ddd64e9741f1"
        config.channel = "pigeon_android"
        config.userNick = null
        config.application = applicationContext as Application
        config.context = this
        config.isAliyunos = false
        //启动CrashReporter
        AliHaAdapter.getInstance().addPlugin(Plugin.crashreporter)
        AliHaAdapter.getInstance().start(config)
    }

    /**
     * 设置基础自定义样式通知示例
     * 1. 详细API介绍请参考:https://help.aliyun.com/document_detail/30066.html#h3-3-4-basiccustompushnotification-api
     */
    private fun setBasicCusNotification() {
        val notification =
            AdvancedCustomPushNotification(
                R.layout.notification_cus_notif,
                R.id.m_icon,
                R.id.m_title,
                R.id.m_text
            ) //创建高级自定义样式通知,设置布局文件以及对应的控件ID
        notification.icon = R.mipmap.app_icon_
        notification.isServerOptionFirst = true //设置服务端配置优先
        notification.isBuildWhenAppInForeground = false //设置当推送到达时如果应用处于前台不创建通知
        CustomNotificationBuilder.getInstance()
            .setCustomNotification(1, notification) //注册该通知,并设置ID为2
    }

}

